package com.xiaoxu.intranetweb.mybatisplusSzappdb.controller.statistics;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSONObject;
import java.net.URLEncoder;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.statistics.StatisticBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.SysUser;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.DailyStatisticsByCpyExportExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.FinancialStatisticsExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.FinancialStatisticsSettlementExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.ProductWeightMoneyNumExportExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.StatisticsVo;
import com.xiaoxu.intranetweb.util.ChineseNumber;
import com.xiaoxu.intranetweb.util.SzResult;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@RequestMapping("/statistic")
public class StatisticController {
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private StatisticBu statisticBu;

    //    Financial Statistics
    @PostMapping("/financialStatistics")
    public SzResult financialStatistics(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        //String paymentTimeStart, String paymentTimeEnd , String deliveryTimeStart, String deliveryTimeEnd, String cpyType, String cpy, String cpyChi, String cpySupply, String cpySupplyChi, String pdtType, String pdt, String ifDelivery, String ifMoney
        String paymentTimeStart = jsonObject.getString("paymentTimeStart");//交款日期(起)
        String paymentTimeEnd = jsonObject.getString("paymentTimeEnd");//交款日期(止)
        String deliveryTimeStart = jsonObject.getString("deliveryTimeStart");//发货日期(起)
        String deliveryTimeEnd = jsonObject.getString("deliveryTimeEnd");//发货日期(止)
        Integer cpyClassId = jsonObject.getInteger("cpyClassId");//单位类型Id
        String cpy = jsonObject.getString("cpy");//收货单位
        String cpyChi = jsonObject.getString("cpyChi");//收货单位(子单位名)
        String cpySupply = jsonObject.getString("cpySupply");//供货单位
        String cpySupplyChi = jsonObject.getString("cpySupplyChi");//供货单位(子单位名)
        Integer pdtClassId = jsonObject.getInteger("pdtClassId");//品种类型Id
//        List<String> pdtName = jsonObject.getJSONArray("pdtName").toJavaList(String.class);可能为空
        List<String> pdtName = null;
        if (jsonObject.getJSONArray("pdtName") != null) {
            pdtName = jsonObject.getJSONArray("pdtName").toJavaList(String.class);
        }
        Integer ifDelivery = jsonObject.getInteger("ifDelivery");
        Integer ifMoney = jsonObject.getInteger("ifMoney");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return SzResult.success(statisticBu.financialStatistics(paymentTimeStart, paymentTimeEnd, deliveryTimeStart, deliveryTimeEnd, cpyClassId, cpy, cpyChi, cpySupply, cpySupplyChi, pdtClassId, pdtName, ifDelivery, ifMoney, token,plantId));
    }

    //    导出financialStatistics的excel
    @PostMapping("/exportFinancialStatistics")
    public void exportFinancialStatistics(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        //        实体类
        List<Map<String, Object>> fields = jsonParam.getObject("fields", List.class);
//        文件名使用utf-8编码
        String filename = jsonParam.getString("filename");
//        数据
        List<Map<String, Object>> ids = jsonParam.getObject("ids", List.class);
//        是否有表头
        Boolean isHeader = jsonParam.getBoolean("isHeader");
//        mode为"current"时，导出当前页，为"all"时，导出所有页，selected时，导出选中数据
        String mode = jsonParam.getString("mode");
//        是否原始数据
        Boolean original = jsonParam.getBoolean("original");
//        分页
        Map<String, String> pager = jsonParam.getObject("pager", Map.class);
//        表格标题
        String sheetName = jsonParam.getString("sheetName");
        Map<String, String> form = jsonParam.getObject("form", Map.class);

//        String paymentTimeStart = form.get("paymentTimeStart");//交款日期(起)
//        String paymentTimeEnd = form.get("paymentTimeEnd");//交款日期(止)
        String paymentTimeStart, paymentTimeEnd, deliveryTimeStart, deliveryTimeEnd, cpy, cpyChi, cpySupply, cpySupplyChi;
        Integer cpyClassId, pdtClassId, ifDelivery, ifMoney;
        List<String> pdtName;
        if (form.get("paymentTimeStart") == null || form.get("paymentTimeEnd") == null) {
            paymentTimeStart = null;
            paymentTimeEnd = null;
        } else {
            paymentTimeStart = form.get("paymentTimeStart");//交款日期(起)
            paymentTimeEnd = form.get("paymentTimeEnd");//交款日期(止)
        }
        if (form.get("deliveryTimeStart") == null || form.get("deliveryTimeEnd") == null) {
            deliveryTimeStart = null;
            deliveryTimeEnd = null;
        } else {
            deliveryTimeStart = form.get("deliveryTimeStart");//发货日期(起)
            deliveryTimeEnd = form.get("deliveryTimeEnd");//发货日期(止)
        }
        if (form.get("cpyClassId") == null||form.get("cpyClassId").equals("")) {
            cpyClassId = null;
        } else {
            cpyClassId = Integer.parseInt(form.get("cpyClassId"));//单位类型Id
        }
        if (form.get("cpy") == null||form.get("cpy").equals("")) {
            cpy = null;
        } else {
            cpy = form.get("cpy");//收货单位
        }
        if (form.get("cpyChi") == null||form.get("cpyChi").equals("")) {
            cpyChi = null;
        } else {
            cpyChi = form.get("cpyChi");//收货单位(子单位名)
        }
        if (form.get("cpySupply") == null||form.get("cpySupply").equals("")) {
            cpySupply = null;
        } else {
            cpySupply = form.get("cpySupply");//供货单位
        }
        if (form.get("cpySupplyChi") == null||form.get("cpySupplyChi").equals("")) {
            cpySupplyChi = null;
        } else {
            cpySupplyChi = form.get("cpySupplyChi");//供货单位(子单位名)
        }
        if (form.get("pdtClassId") == null||form.get("pdtClassId").equals("")) {
            pdtClassId = null;
        } else {
            pdtClassId = Integer.parseInt(form.get("pdtClassId"));//品种类型Id
        }
        if (form.get("pdtName") == null||form.get("pdtName").equals("")) {
            pdtName = null;
        } else {
            pdtName = Collections.singletonList(form.get("pdtName"));//品种名
        }
        if (form.get("ifDelivery") == null||form.get("ifDelivery").equals("")) {
            ifDelivery = null;
        } else {
            ifDelivery = Integer.parseInt(form.get("ifDelivery"));//是否发货
        }
        if (form.get("ifMoney") == null||form.get("ifMoney").equals("")) {
            ifMoney = null;
        } else {
            ifMoney = Integer.parseInt(form.get("ifMoney"));//是否交款
        }
        List<StatisticsVo> statistics = statisticBu.exportFinancialStatistics(paymentTimeStart, paymentTimeEnd, deliveryTimeStart, deliveryTimeEnd, cpyClassId, cpy, cpyChi, cpySupply, cpySupplyChi, pdtClassId, pdtName, ifDelivery, ifMoney, token,plantId);
//        statistics和FinancialStatisticsExcelEn一模一样
        List<FinancialStatisticsExcelEn> financialStatistics = new ArrayList<>();
        for (StatisticsVo vo : statistics) {
            FinancialStatisticsExcelEn en = new FinancialStatisticsExcelEn();
            BeanUtils.copyProperties(vo, en);
            financialStatistics.add(en);
        }
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        if (filename == null || filename.equals("")) {
            filename = "财务统计表" + paymentTimeStart + "~" + paymentTimeEnd;
        }
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), FinancialStatisticsExcelEn.class).sheet(filename).doWrite(financialStatistics);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    //    导出财务统计结算单
    @PostMapping("/exportFinancialStatisticsSettlement")
    public void exportFinancialStatisticsSettlement(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());

//        String paymentTimeStart = form.get("paymentTimeStart");//交款日期(起)
//        String paymentTimeEnd = form.get("paymentTimeEnd");//交款日期(止)
        String paymentTimeStart = "", paymentTimeEnd = "", deliveryTimeStart = "", deliveryTimeEnd = "", cpy = "", cpyChi = "", cpySupply = "", cpySupplyChi = "";
        Integer cpyClassId = null, pdtClassId = null, ifDelivery = null, ifMoney = null;
        List<String> pdtName = null;
        if (jsonParam != null) {
            if (jsonParam.get("paymentTimeStart") == null || jsonParam.get("paymentTimeEnd") == null || jsonParam.getString("paymentTimeStart").equals("") || jsonParam.getString("paymentTimeEnd").equals("")) {
                paymentTimeStart = null;
                paymentTimeEnd = null;
            } else {
                paymentTimeStart = jsonParam.getString("paymentTimeStart");//交款日期(起)
                paymentTimeEnd = jsonParam.getString("paymentTimeEnd");//交款日期(止)
            }
            if (jsonParam.get("deliveryTimeStart") == null || jsonParam.get("deliveryTimeEnd") == null || jsonParam.getString("deliveryTimeStart").equals("") || jsonParam.getString("deliveryTimeEnd").equals("")) {
                deliveryTimeStart = null;
                deliveryTimeEnd = null;
            } else {
                deliveryTimeStart = jsonParam.get("deliveryTimeStart").toString();//发货日期(起)
                deliveryTimeEnd = jsonParam.get("deliveryTimeEnd").toString();//发货日期(止)
            }
            if (jsonParam.get("cpyClassId") != null) {
                cpyClassId = jsonParam.getInteger("cpyClassId");//单位类型Id
            }
            if (jsonParam.get("cpy") == null || jsonParam.getString("cpy").equals("")) {
                cpy = null;
            } else {
                cpy = jsonParam.get("cpy").toString();//收货单位
            }
            if (jsonParam.get("cpyChi") == null || jsonParam.getString("cpyChi").equals("")) {
                cpyChi = null;
            } else {
                cpyChi = jsonParam.getString("cpyChi");//收货单位(子单位名)
            }
            if (jsonParam.get("cpySupply") == null || jsonParam.getString("cpySupply").equals("")) {
                cpySupply = null;
            } else {
                cpySupply = jsonParam.getString("cpySupply");//供货单位
            }
            if (jsonParam.get("cpySupplyChi") == null || jsonParam.getString("cpySupplyChi").equals("")) {
                cpySupplyChi = null;
            } else {
                cpySupplyChi = jsonParam.getString("cpySupplyChi");//供货单位(子单位名)
            }
            if (jsonParam.get("pdtClassId") != null) {
                pdtClassId = jsonParam.getInteger("pdtClassId");//品种类型Id
            } else {
                jsonParam.getInteger("pdtClassId");
            }
            if (jsonParam.get("pdtName") != null) {
                pdtName = jsonParam.getJSONArray("pdtName").toJavaList(String.class);//品种名称
            }
            if (jsonParam.get("ifDelivery") != null) {
                ifDelivery = jsonParam.getInteger("ifDelivery");//是否发货
            }
            if (jsonParam.get("ifMoney") != null) {
                ifMoney = jsonParam.getInteger("ifMoney");//是否交款
            }
        }
        List<StatisticsVo> statistics = statisticBu.exportFinancialStatisticsSettlement(paymentTimeStart, paymentTimeEnd, deliveryTimeStart, deliveryTimeEnd, cpyClassId, cpy, cpyChi, cpySupply, cpySupplyChi, pdtClassId, pdtName, ifDelivery, ifMoney, token,plantId);
        Workbook workbook = new XSSFWorkbook();
        try {
            // 创建标题样式
            CellStyle titleStyle = workbook.createCellStyle();
            titleStyle.setAlignment(HorizontalAlignment.CENTER);
            Font titleFont = workbook.createFont();
            titleFont.setFontHeightInPoints((short) 16);
            titleStyle.setFont(titleFont);

            // 创建表头样式
            CellStyle headerStyle = workbook.createCellStyle();
            headerStyle.setAlignment(HorizontalAlignment.CENTER);
            Font headerFont = workbook.createFont();
            headerFont.setFontHeightInPoints((short) 12);
//        边框
            headerStyle.setBorderBottom(BorderStyle.THIN);
            headerStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
            headerStyle.setBorderLeft(BorderStyle.THIN);
            headerStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
            headerStyle.setBorderRight(BorderStyle.THIN);
            headerStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
            headerStyle.setBorderTop(BorderStyle.THIN);
            headerStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
//        蓝色内容
            headerFont.setColor(IndexedColors.BLUE.getIndex());
            headerStyle.setFont(headerFont);

            // 创建合计和大写样式
            CellStyle totalStyle = workbook.createCellStyle();
            totalStyle.setAlignment(HorizontalAlignment.CENTER);
            Font totalFont = workbook.createFont();
//        边框
            totalStyle.setBorderBottom(BorderStyle.THIN);
            totalStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
            totalStyle.setBorderLeft(BorderStyle.THIN);
            totalStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
            totalStyle.setBorderRight(BorderStyle.THIN);
            totalStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
            totalStyle.setBorderTop(BorderStyle.THIN);
            totalStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
            totalFont.setColor(IndexedColors.BLUE.getIndex());
            totalStyle.setFont(totalFont);
            CellStyle style = workbook.createCellStyle();
            style.setBorderBottom(BorderStyle.THIN);
            style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
            style.setBorderLeft(BorderStyle.THIN);
            style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
            style.setBorderRight(BorderStyle.THIN);
            style.setRightBorderColor(IndexedColors.BLACK.getIndex());
            style.setBorderTop(BorderStyle.THIN);
            style.setTopBorderColor(IndexedColors.BLACK.getIndex());
            for (int i = 0; i < statistics.size(); i++) {
                FinancialStatisticsSettlementExcelEn en = new FinancialStatisticsSettlementExcelEn();
                BeanUtils.copyProperties(statistics.get(i), en);

                List<FinancialStatisticsSettlementExcelEn> financialStatistics = new ArrayList<>();
                for (StatisticsVo vo : en.getStatisticsVoList()) {
                    FinancialStatisticsSettlementExcelEn en1 = new FinancialStatisticsSettlementExcelEn();
                    BeanUtils.copyProperties(vo, en1);
                    financialStatistics.add(en1);
                }

                Sheet sheet = workbook.createSheet(statistics.get(i).getCpyCo());

                // 创建标题行
                Row titleRow = sheet.createRow(0);
                Cell titleCell = titleRow.createCell(0);
                titleCell.setCellStyle(titleStyle);
                titleCell.setCellValue(statistics.get(i).getCpySupplyCoName() + "【" + deliveryTimeStart + "~" + deliveryTimeEnd + "】");
                // 合并单元格
                sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));

                // 创建表头行
                Row headerRow = sheet.createRow(1);
                headerRow.createCell(0).setCellValue("收货单位");
                headerRow.createCell(1).setCellValue("品种");
                headerRow.createCell(2).setCellValue("价格");
                headerRow.createCell(3).setCellValue("车数");
                headerRow.createCell(4).setCellValue("本期发货量");
                headerRow.createCell(5).setCellValue("本期发货额");
                headerRow.createCell(6).setCellValue("发票类型");

// 设置列宽
                sheet.setColumnWidth(0, 30 * 256);
                sheet.setColumnWidth(1, 11 * 256);
                sheet.setColumnWidth(2, 8 * 256);
                sheet.setColumnWidth(3, 8 * 256);
                sheet.setColumnWidth(4, 11 * 256);
                sheet.setColumnWidth(5, 13 * 256);
                sheet.setColumnWidth(6, 9 * 256);
                headerRow.getCell(0).setCellStyle(headerStyle);
                headerRow.getCell(1).setCellStyle(headerStyle);
                headerRow.getCell(2).setCellStyle(headerStyle);
                headerRow.getCell(3).setCellStyle(headerStyle);
                headerRow.getCell(4).setCellStyle(headerStyle);
                headerRow.getCell(5).setCellStyle(headerStyle);
                headerRow.getCell(6).setCellStyle(headerStyle);
                // 写入数据
                for (int j = 0; j < financialStatistics.size(); j++) {
                    Row row = sheet.createRow(j + 2);
                    row.createCell(0).setCellValue(financialStatistics.get(j).getCpyName());
                    row.createCell(1).setCellValue(financialStatistics.get(j).getPdtName());
                    row.createCell(2).setCellValue(financialStatistics.get(j).getPrice().toString());
                    row.createCell(3).setCellValue(financialStatistics.get(j).getCarNum().toString());
                    row.createCell(4).setCellValue(financialStatistics.get(j).getThisPeriodDelivery().toString());
                    row.createCell(5).setCellValue(financialStatistics.get(j).getThisPeriodDeliveryMoney().toString());
                    row.createCell(6).setCellValue("");
//        使用style样式
                    row.getCell(0).setCellStyle(style);
                    row.getCell(1).setCellStyle(style);
                    row.getCell(2).setCellStyle(style);
                    row.getCell(3).setCellStyle(style);
                    row.getCell(4).setCellStyle(style);
                    row.getCell(5).setCellStyle(style);
                    row.getCell(6).setCellStyle(style);

                }
                // 创建合计行
// 创建合计行
                Row totalRow = sheet.createRow(sheet.getLastRowNum() + 1);
                Cell totalCell = totalRow.createCell(0);
                totalCell.setCellValue("合计:");
                totalCell.setCellStyle(totalStyle);
                sheet.addMergedRegion(new CellRangeAddress(sheet.getLastRowNum(), sheet.getLastRowNum(), 0, 4));
                totalRow.createCell(5).setCellValue(statistics.get(i).getThisPeriodDeliveryMoney().toString());
                totalRow.getCell(5).setCellStyle(style);
                // 为剩下的空格子创建空的单元格并应用样式
                for (int j = 6; j < 7; j++) {
                    totalRow.createCell(j).setCellStyle(style);
                }
// 创建大写行
                Row totalRow1 = sheet.createRow(sheet.getLastRowNum() + 1);
                Cell totalCell1 = totalRow1.createCell(0);
                totalCell1.setCellValue("大写:");
                totalCell1.setCellStyle(totalStyle);
                sheet.addMergedRegion(new CellRangeAddress(sheet.getLastRowNum(), sheet.getLastRowNum(), 1, 5));
                totalRow1.createCell(1).setCellValue(ChineseNumber.getChineseNumber(statistics.get(i).getThisPeriodDeliveryMoney().toString()));
                totalRow1.getCell(1).setCellStyle(style);
                // 为剩下的空格子创建空的单元格并应用样式
                for (int j = 2; j < 7; j++) {
                    totalRow1.createCell(j).setCellStyle(style);
                }
//            再加一行空的然后只有下方画上线
//                sheet.addMergedRegion(new CellRangeAddress(sheet.getLastRowNum(), sheet.getLastRowNum(), 0, 6));

//            再加一行前6格合并然后写上（打印：）
//            最后一格写user.getTrueName
                Row totalRow3 = sheet.createRow(sheet.getLastRowNum() + 1);
                Cell totalCell3 = totalRow3.createCell(0);
                totalCell3.setCellValue("部门负责人：        业务：             统计：            财务：              打印：");
                sheet.addMergedRegion(new CellRangeAddress(sheet.getLastRowNum(), sheet.getLastRowNum(), 0, 5));
                totalRow3.createCell(6).setCellValue(user.getTrueName());
            }
        } finally {
            workbook.write(response.getOutputStream());
            workbook.close();
        }
    }


    @GetMapping("/dailyStatistics")
    public SzResult dailyStatistics(@RequestParam(value = "dateTime", required = false) String dateTime,
                                    @RequestParam(value = "coSupply", required = false) String coSupply,
                                    @RequestParam(value = "coSupplyChi", required = false) String coSupplyChi,
                                    @RequestParam(value = "co", required = false) String co,
                                    @RequestParam(value = "chiCo", required = false) String chiCo,
                                    @RequestParam(value = "pdtClassId", required = false) Integer pdtClassId,
                                    @RequestParam(value = "product", required = false) List<String> product,
                                    @RequestParam(value = "truckno", required = false) String truckno,
                                    @RequestParam(value = "iccardno", required = false) String iccardno,
                                    @RequestParam(value = "isEmpty", required = false) Integer isEmpty,
                                    @RequestParam(value = "cpyClass", required = false) String cpyClass,
                                    @RequestParam(value = "pdtClass", required = false) String pdtClass,
                                    HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return statisticBu.dailyStatistics(dateTime, coSupply, coSupplyChi, co, chiCo, pdtClassId, product, truckno, iccardno, isEmpty, cpyClass, pdtClass, token,plantId);
    }


    /**
     * 日报导表
     */
    @PostMapping("dailyStatisticsExportExcel")
    public void dailyStatisticsExportExcel(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
//        String plantId = null;
//        if (token != null) {
//            plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
//        }


        //        实体类
        List<Map<String, Object>> fields = jsonParam.getObject("fields", List.class);
//        文件名使用utf-8编码
        String filename = jsonParam.getString("filename");
//        数据
        List<Map<String, Object>> ids = jsonParam.getObject("ids", List.class);
//        是否有表头
        Boolean isHeader = jsonParam.getBoolean("isHeader");
//        mode为"current"时，导出当前页，为"all"时，导出所有页，selected时，导出选中数据
        String mode = jsonParam.getString("mode");
//        是否原始数据
        Boolean original = jsonParam.getBoolean("original");
//        分页
        Map<String, String> pager = jsonParam.getObject("pager", Map.class);
//        表格标题
        String sheetName = jsonParam.getString("sheetName");
        Map form = jsonParam.getObject("form", Map.class);
        List<String> product = new ArrayList<>();
        if (form.get("product") != null && !form.get("product").equals("null")) {
            product = Collections.singletonList(form.get("product").toString());
        }
        String dateTime = null;
        String startTime = null;
        String endTime = null;
        if (form.get("dateTime") != null && !form.get("dateTime").equals("null")) {
            dateTime = form.get("dateTime").toString();
             startTime = dateTime + " 00:00:00";
             endTime = dateTime + " 23:59:59";
        }

        String truckNo = null;
        if (form.get("truckNo") != null && !form.get("truckNo").equals("null")) {
            truckNo = form.get("truckNo").toString();
        }
        String icCardNo = null;
        if (form.get("icCardNo") != null && !form.get("icCardNo").equals("null")) {
            icCardNo = form.get("icCardNo").toString();
        }
        Integer pdtClassId = null;
        if (form.get("pdtClassId") != null && !form.get("pdtClassId").equals("null")) {
            pdtClassId = Integer.valueOf(form.get("pdtClassId").toString());
        }
        String coSupply = null;
        if (form.get("coSupply") != null && !form.get("coSupply").equals("null")) {
            coSupply = form.get("coSupply").toString();
        }
        String coSupplyChi = null;
        if (form.get("coSupplyChi") != null && !form.get("coSupplyChi").equals("null")) {
            coSupplyChi = form.get("coSupplyChi").toString();
        }
        String co = null;
        if (form.get("co") != null && !form.get("co").equals("null")) {
            co = form.get("co").toString();
        }
        String coChi = null;
        if (form.get("coChi") != null && !form.get("coChi").equals("null")) {
            coChi = form.get("coChi").toString();
        }

        Future<List<ProductWeightMoneyNumExportExcelEn>> listFuture = statisticBu.dailyStatisticsExportExcel(fields, ids, filename, isHeader, mode, original, pager, pdtClassId, product, startTime, endTime, truckNo, icCardNo, sheetName, response, plantId, coSupply, coSupplyChi, co, coChi);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        BorderStyle borderStyle = BorderStyle.THIN;
        short borderColor = IndexedColors.BLACK.getIndex();
        contentWriteCellStyle.setBorderTop(borderStyle);
        contentWriteCellStyle.setBorderBottom(borderStyle);
        contentWriteCellStyle.setBorderLeft(borderStyle);
        contentWriteCellStyle.setBorderRight(borderStyle);
        contentWriteCellStyle.setTopBorderColor(borderColor);
        contentWriteCellStyle.setBottomBorderColor(borderColor);
        contentWriteCellStyle.setLeftBorderColor(borderColor);
        contentWriteCellStyle.setRightBorderColor(borderColor);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(null, contentWriteCellStyle);

        List<ProductWeightMoneyNumExportExcelEn> productWeightMoneyNumExportExcelEn = listFuture.get();
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        if (filename == null || filename.equals("")) {
            filename = "按品种"+dateTime;
        }

        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("日报统计-"+dateTime, "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ProductWeightMoneyNumExportExcelEn.class)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .sheet("按品种").doWrite(productWeightMoneyNumExportExcelEn);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }



    @GetMapping("/dailyStatisticsByCpy")
    public SzResult dailyStatisticsByCpy(@RequestParam(value = "dateTime", required = false) String dateTime,
                                    @RequestParam(value = "coSupply", required = false) String coSupply,
                                    @RequestParam(value = "coSupplyChi", required = false) String coSupplyChi,
                                    @RequestParam(value = "co", required = false) String co,
                                    @RequestParam(value = "chiCo", required = false) String chiCo,
                                    @RequestParam(value = "pdtClassId", required = false) Integer pdtClassId,
                                    @RequestParam(value = "product", required = false) List<String> product,
                                    @RequestParam(value = "truckno", required = false) String truckno,
                                    @RequestParam(value = "iccardno", required = false) String iccardno,
                                    @RequestParam(value = "isEmpty", required = false) Integer isEmpty,
                                    @RequestParam(value = "cpyClass", required = false) String cpyClass,
                                    @RequestParam(value = "pdtClass", required = false) String pdtClass,
                                    HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return statisticBu.dailyStatisticsByCpy(dateTime, coSupply, coSupplyChi, co, chiCo, pdtClassId, product, truckno, iccardno, isEmpty, cpyClass, pdtClass, token,plantId);
    }



    @PostMapping("dailyStatisticsByCpyExportExcel")
    public void dailyStatisticsByCpyExportExcel(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
//        String plantId = null;
//        if (token != null) {
//            plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
//        }
        //        实体类
        List<Map<String, Object>> fields = jsonParam.getObject("fields", List.class);
//        文件名使用utf-8编码
        String filename = jsonParam.getString("filename");
//        数据
        List<Map<String, Object>> ids = jsonParam.getObject("ids", List.class);
//        是否有表头
        Boolean isHeader = jsonParam.getBoolean("isHeader");
//        mode为"current"时，导出当前页，为"all"时，导出所有页，selected时，导出选中数据
        String mode = jsonParam.getString("mode");
//        是否原始数据
        Boolean original = jsonParam.getBoolean("original");
//        分页
        Map<String, String> pager = jsonParam.getObject("pager", Map.class);
//        表格标题
        String sheetName = jsonParam.getString("sheetName");
        Map form = jsonParam.getObject("form", Map.class);
        List<String> product = new ArrayList<>();
        if (form.get("product") != null && !form.get("product").equals("null")) {
            product = Collections.singletonList(form.get("product").toString());
        }
        String dateTime = null;
        String startTime = null;
        String endTime = null;
        if (form.get("dateTime") != null && !form.get("dateTime").equals("null")) {
            dateTime = form.get("dateTime").toString();
            startTime = dateTime + " 00:00:00";
            endTime = dateTime + " 23:59:59";
        }

        String truckNo = null;
        if (form.get("truckNo") != null && !form.get("truckNo").equals("null")) {
            truckNo = form.get("truckNo").toString();
        }
        String icCardNo = null;
        if (form.get("icCardNo") != null && !form.get("icCardNo").equals("null")) {
            icCardNo = form.get("icCardNo").toString();
        }
        Integer pdtClassId = null;
        if (form.get("pdtClassId") != null && !form.get("pdtClassId").equals("null")) {
            pdtClassId = Integer.valueOf(form.get("pdtClassId").toString());
        }
        String coSupply = null;
        if (form.get("coSupply") != null && !form.get("coSupply").equals("null")) {
            coSupply = form.get("coSupply").toString();
        }
        String coSupplyChi = null;
        if (form.get("coSupplyChi") != null && !form.get("coSupplyChi").equals("null")) {
            coSupplyChi = form.get("coSupplyChi").toString();
        }
        String co = null;
        if (form.get("co") != null && !form.get("co").equals("null")) {
            co = form.get("co").toString();
        }
        String coChi = null;
        if (form.get("coChi") != null && !form.get("coChi").equals("null")) {
            coChi = form.get("coChi").toString();
        }
        String cpyClass = null;
        if (form.get("cpyClass") != null && !form.get("cpyClass").equals("null")) {
            cpyClass = form.get("cpyClass").toString();
        }

        Future<List<DailyStatisticsByCpyExportExcelEn>> listFuture = statisticBu.dailyStatisticsByCpy(fields, ids, filename, isHeader, mode, original, pager, pdtClassId, product, startTime, endTime, truckNo, icCardNo, sheetName, response, plantId, coSupply, coSupplyChi, co, coChi);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        BorderStyle borderStyle = BorderStyle.THIN;
        short borderColor = IndexedColors.BLACK.getIndex();
        contentWriteCellStyle.setBorderTop(borderStyle);
        contentWriteCellStyle.setBorderBottom(borderStyle);
        contentWriteCellStyle.setBorderLeft(borderStyle);
        contentWriteCellStyle.setBorderRight(borderStyle);
        contentWriteCellStyle.setTopBorderColor(borderColor);
        contentWriteCellStyle.setBottomBorderColor(borderColor);
        contentWriteCellStyle.setLeftBorderColor(borderColor);
        contentWriteCellStyle.setRightBorderColor(borderColor);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(null, contentWriteCellStyle);

        List<DailyStatisticsByCpyExportExcelEn> productWeightMoneyNumExportExcelEn = listFuture.get();
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        if (filename == null || filename.equals("")) {
            filename = "按品种";
        }

        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), DailyStatisticsByCpyExportExcelEn.class)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .sheet("按品种").doWrite(productWeightMoneyNumExportExcelEn);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }
}
